﻿var tree;
var bmNewTree;
var root;
var currentNode;
var library_id;
var library_name;
var frameHeight;
var gridStore;
// 业务对象
var currentCategory = "";// 当前节点对应的分类
Ext.onReady(function () {
    Ext.BLANK_IMAGE_URL = application_STATIC_SERVER + 'jmda-static/js/extjs3/images/default/s.gif';
    Ext.QuickTips.init();
    // 刷新按钮
    var btnRefresh = new Ext.Action({
        text: '刷新',
        tooltip: '刷新模型库',
        iconCls: 'iconRefresh',
        handler: function () {
            root.reload();
        }
    });
    //新建按钮
    var btnExpand = new Ext.Action({
        text: '新建',
        tooltip: '新建....',
        iconCls: 'iconNew',
        handler: function () {
            openModelCreateWin();
        }
    });
    viewport = new Ext.Viewport({
        layout: 'border',
        items: [{
            region: 'west',
            layoutConfig: {
                animate: true
            },
            title: '业务模型',
            split: true,
            width: 200,
            minSize: 175,
            maxSize: 400,
            collapsible: false,
            tbar: [btnExpand, btnRefresh],
            contentEl: 'westPanel'
        }, new Ext.TabPanel({
            id: 'tabPanel',
            region: 'center',
            margins: '3 3 3 0',
            activeTab: 0,
            defaults: {
                autoScroll: true
            },
            layoutConfig: {
                animate: true
            },
            items: [{
                id: 'tab_first',
                title: '欢迎页',
                closable: false,
                contentEl: 'tabList'
            }],
            listeners: {
                contextmenu: function (tp, p, e) {
                    if (!p.closable)
                        return;
                    var menus = new Ext.menu.Menu([{
                        xtype: "button",
                        text: '关闭',
                        pressed: true,
                        handler: function () {
                            Ext.getCmp('tabPanel').remove(p);
                        }
                    }, {
                        xtype: "button",
                        text: '关闭全部页签',
                        pressed: true,
                        handler: function () {
                            var portalTab = Ext.getCmp('tabPanel');
                            portalTab.items.each(function (item) {
                                if (item.closable) {
                                    portalTab.remove(item);
                                }
                            });
                        }
                    }, {
                        xtype: "button",
                        text: '关闭其他页签',
                        pressed: true,
                        handler: function () {
                            var portalTab = Ext.getCmp('tabPanel');
                            portalTab.items.each(function (item) {
                                if (item.closable && item.id != p.id) {
                                    portalTab.remove(item);
                                }
                            });
                        }
                    }]);
                    menus.showAt(e.getPoint());
                }
            }
        })]
    });
    //应用模型库异步树,加载到id为treeBMRoot的元素中
    root = new Ext.tree.AsyncTreeNode({
        id: "root",
        iconCls: 'tree_root',
        draggable: false,
        text: "应用模型库",
        cls: "treeBMRoot",
        expanded: true
    });

    tree = new Ext.tree.TreePanel({
        el: "treePanel",
        loader: new Ext.tree.TreeLoader({
            url: basePath + "repository/application/getTreeJson"
        }),
        lines: true,
        animate: true,
        border: false,
        bodyStyle: "overflow:scroll;",
        ddGroup: 'navigationDD',
        collapsible: false,
        autoScroll: true,
        root: root,
        listeners: {
            click: treeOnClick
        }
    });
    tree.render();
    root.select();
    // 右键菜单

});
function treeOnClick(n, e) {
    if (n.id == 'root') {
        createViewTab('root', '应用模型库', '', basePath + 'repository/application/getApplicationGridPage', true);
        currentNode = n;
    } else if (n.id.indexOf('F_') != -1) {
        var applicationId = n.id.substring(2);
        createViewTab('first_floor', n.text, '', basePath + 'repository/form/getFormGridPage?applicationId=' + applicationId, true);
        currentNode = n;
    } else if (n.id.indexOf('DD_') != -1) {
        var dd_id = n.id.substring(3);
        createViewTab('first_floor', n.text, '', basePath + 'dictionary/getPage.wf?model_lib_id=' + dd_id, true);
        currentNode = n;
    } else if (n.id.indexOf('LIST_') != -1) {
        var dv_id = n.id.substring(5);
        createViewTab('first_floor', n.text, '', basePath + 'repository/worklist/getGridPage?applicationId=' + dv_id, true);
        currentNode = n;
    } else if (n.id.indexOf('FORM_') != -1) {
        var form_id = n.id.substring(5);
        createViewTab('second_floor_form', n.text, '', basePath + 'repository/form/openForm?formId=' + form_id, true);
        currentNode = n;
    } else if (n.id.indexOf('DICTIONARY_') != -1) {
        var DATADIC_id = n.id.substring(11);
        createViewTab('second_floor_dictionary', n.text, '', basePath + 'dictionary/pub.wf?DATADIC_NAME=' + n.text + '&DATADIC_id=' + DATADIC_id, true);
        currentNode = n;
    } else if (n.id.indexOf('LISTDATA_') != -1) {
        var DATAVIEW_id = n.id.substring(9);
        createViewTab('second_floor_worklist', n.text, '', basePath + 'repository/worklist/openWorkList?worklistid=' + DATAVIEW_id, true);
        currentNode = n;
    } else {
    }

}
function createViewTab(tabId, tabTitle, iconCls, src, isRefresh, config) {
    if (typeof (isRefresh) == "undefined") {
        isRefresh = false;
    }
    var frmId = tabId + '_Frame';
    var tabs = Ext.getCmp("tabPanel");
    var tab = tabs.getItem(tabId);
    if (tab == null) {
        tab = {
            id: tabId,
            title: tabTitle,
            tabTip: tabTitle,
            closable: true,
            autoScroll: true,
            iconCls: iconCls,
            html: "<iframe id='" + frmId + "' name='" + frmId + "' src='" + src + "' frameborder=0 width=100% height=100%></iframe>"
        };

        Ext.apply(tab, config || {});
        tabs.add(tab).show();
    } else {
        if (isRefresh) {// 刷新打开的tab页
            tab.addListener('show', function () {
                document.getElementById(frmId).src = src;
            });
        }
        tab.setTitle(tabTitle);
        tab.show();
    }
}

// 刷新当前打开树节点
function refreshCurrNode() {
    if (currentNode) {
        if (!currentNode.leaf) {
            currentNode.reload();
        } else {
            currentNode.parentNode.reload();
        }
    }
}
// 刷新指定ID的树节点
function regreshNodeById(id, selectNodeId) {
    var node = tree.getNodeById(id);
    if (node) {
        if (!node.leaf) {
            node.reload();
        } else {
            node.parentNode.reload();
        }
        if (typeof (selectNodeId) != "undefined") {
            setTimeout(function () {
                if (tree.getNodeById(selectNodeId))
                    tree.getNodeById(selectNodeId).select();
            }, 500);
        }
    }
}

var newType = null;
var newWin;
function openModelCreateWin() {
    var selectId = tree.getSelectionModel().selNode.id;
    if (!newWin) {
        bmNewTree = new Ext.tree.TreePanel({
            el: 'BMNewTree',
            animate: true,
            autoScroll: true,
            containerScroll: true,
            lines: true,
            border: false,
            rootVisible: true,
            enableDD: false
        });
        bmNewTreeRoot = new Ext.tree.TreeNode({
            id: 'NODE_ID_BMNew_ROOT',
            text: '应用业务模型',
            type: "ROOT",
            cls: 'treeBMRoot'
        });

        var new_form = new Ext.tree.TreeNode({
            id: 'NODE_ID_BMNew_Form',
            text: 'Form表单模型',
            type: 'FM',
            cls: 'treeBMForm'
        });
//		var new_dataDic = new Ext.tree.TreeNode({
//			id : 'NODE_ID_BMNew_DATADIC',
//			text : '数据字典',
//			type : 'DATADIC',
//			cls : 'dictionary'
//		});
        var new_dataView = new Ext.tree.TreeNode({
            id: 'NODE_ID_BMNew_DATAVIEW',
            text: '数据列表',
            type: 'DATAVIEW',
            cls: 'worklistview'
        });
        // 模型库分类
        var new_ms = new Ext.tree.TreeNode({
            id: 'NODE_ID_BMNew_ModuleStore',
            text: '模型库分类',
            type: 'MS',
            cls: 'treeBMCategory'
        });
        bmNewTreeRoot.appendChild(new_form);
//		bmNewTreeRoot.appendChild(new_dataDic);
        bmNewTreeRoot.appendChild(new_dataView);
        bmNewTreeRoot.appendChild(new_ms);
        bmNewTree.setRootNode(bmNewTreeRoot);
        bmNewTree.render();
        bmNewTreeRoot.expand(true, true);

        // 节点单击事件
        bmNewTree.on('click', function (node) {
            newType = node.attributes.type;
        });

        newWin = new Ext.Window({
            el: 'BMNewWindow',
            title: '新建...',
            layout: 'fit',
            width: 250,
            height: 300,
            closeAction: 'hide',
            plain: true,
            items: bmNewTree,
            modal: true,
            keys: [{
                key: 27,
                scope: this,
                fn: function () {
                    newWin.hide();
                }
            }],
            buttonAlign: 'center',
            buttons: [{
                text: '确定',
                handler: function () {
                    if (newType == null || newType == "ROOT") {
                        Ext.Msg.alert('提示', '请选择新建类型');
                    } else {
                        newWin.hide();
                        addItem();
                        //newType = null;
                    }
                }
            }, {
                text: '关闭',
                handler: function () {
                    newWin.hide();
                }
            }]
        });
    }
    newWin.show();
}

function addItem() {
    if (newType == 'MS') {
        //openModuleStoreWin('');
        openSimpleExtWindow('新建模型分类', 500, 270, basePath + "repository/application/getCreatePage?applicationId=" + library_id + "&typeName=模型分类");
        if (activeDialog) {
            activeDialog.purgeListeners();
            activeDialog.addListener('show', handleShow);
            activeDialog.addListener('beforehide', handleHide);
            activeDialog.show();
        }
    } else if (newType == 'FM') {
        openSimpleExtWindow('新建表单', 500, 270, basePath + "repository/application/getCreatePage?applicationId=" + library_id + "&typeName=表单");
        if (activeDialog) {
            activeDialog.purgeListeners();
            activeDialog.addListener('show', handleShow);
            activeDialog.addListener('beforehide', handleHide);
            activeDialog.show();
        }
    } else if (newType == 'DATADIC') {
        openSimpleExtWindow('新建数据字典', 500, 300, basePath + "dictionary/create.wf?groupId=" + library_id);
        if (activeDialog) {
            activeDialog.purgeListeners();
            activeDialog.addListener('show', handleShow);
            activeDialog.addListener('beforehide', handleHide);
            activeDialog.show();
        }
    } else if (newType == 'DATAVIEW') {
        openSimpleExtWindow('新建数据列表', 500, 300, basePath + "repository/application/getCreatePage?applicationId=" + library_id + "&typeName=数据列表");
        if (activeDialog) {
            activeDialog.purgeListeners();
            activeDialog.addListener('show', handleShow);
            activeDialog.addListener('beforehide', handleHide);
            activeDialog.show();
        }
    } else {
        alert('other');
    }
}
function openModuleStoreWin(applicationId) {
    Ext.MessageBox.prompt('提示', '请输入应用名称:', function (btn, text) {
        if (text.indexOf(' ') != -1) {
            Ext.Msg.alert('提示', '不允许输入空格等特殊字符');
            return false;
        } else {
            createCategory(btn, text, applicationId);
            return false;
        }
    });
}

function createCategory(btn, categoryName, applicationId) {
    if (btn == 'ok') {
        if (categoryName == '') {
            Ext.Msg.alert('提示', '模型分类名称不允许为空！');
            return false;
        }
        Ext.Ajax.request({
            url: basePath + 'repository/application/storeApplication',
            method: 'POST',
            params: {
                applicatioName: categoryName,
                applicationId: applicationId
            },
            failure: function (response, options) {
                Ext.Msg.alert('操作失败', '操作失败！可能是网络超时！');
                return false;
            },
            success: function (response, options) {
                if (response.responseText == '0') {
                    Ext.Msg.confirm('错误', '【' + categoryName + '】模型分类已存在\n是否继续创建？', function (btn) {
                        if (btn == 'yes') {
                            openModuleStoreWin();
                        }
                    });
                    return false;
                }
                try {
                    root.reload();
                    document.getElementById('root_Frame').src = basePath + 'repository/application/getApplicationGridPage';
                } catch (e) {
                }
            }
        });
    }
    return false;
}